package com.zheng.study.base.entity.interceptor;

import com.zheng.study.base.utils.Identities;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;

/**
 * 过滤器 - 自动填充创建、更新时间
 * ============================================================================
 * author : fallenpanda
 * createDate:  2016-07-13。
 * ============================================================================
 */
@Component
public class EntityInterceptor extends EmptyInterceptor {
	private static final long serialVersionUID = 8816229775614147052L;

	private static final String CREATE_DATE = "createTime"; //创建时间
	private static final String MODIFY_DATE = "modifyTime"; //修改时间
	private static final String TIME_STAMP = "timestamp";// 随机uuid

	// 保存数据时回调此方法
	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types){
		Date createDate = new Date();
		for(int i=0;i<propertyNames.length;i++){
			if(CREATE_DATE.equals(propertyNames[i])){
				if(state[i]==null) state[i] = createDate;
			}else if(MODIFY_DATE.equals(propertyNames[i])){
				state[i]=createDate;
			}else if(TIME_STAMP.equals(propertyNames[i])){
				if(state[i]==null){
					String timestamp = Identities.uuid2();
					state[i] = timestamp;
				}
			}
		}
		return true;
	}

	//更新数据时回调此方法
	@Override
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types){
		Date updateDate = new Date();
		for(int i=0;i<propertyNames.length;i++){
			if(MODIFY_DATE.equals(propertyNames[i])){
				currentState[i] = updateDate;
			}
		}
		return true;
	}

}
